package com.ms.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ms.common.utils.PageUtils;
import com.ms.common.utils.Query;
import com.ms.content.dao.BargainingItemDao;
import com.ms.content.dao.BargainingRecordDao;
import com.ms.content.dao.GoodsDao;
import com.ms.content.entity.BargainingItemEntity;
import com.ms.content.entity.BargainingRecordEntity;
import com.ms.content.entity.GoodsEntity;
import com.ms.content.feginDy.FeginService;
import com.ms.content.service.BargainingRecordService;
import com.ms.content.service.GoodsService;
import com.ms.content.util.SnowflakeIdWorker;
import com.ms.content.vo.kVo;
import com.mysql.fabric.xmlrpc.base.Array;
import com.mysql.fabric.xmlrpc.base.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ms.content.dao.BargainActivityDao;
import com.ms.content.entity.BargainActivityEntity;
import com.ms.content.service.BargainActivityService;


@Service("bargainActivityService")
public class BargainActivityServiceImpl extends ServiceImpl<BargainActivityDao, BargainActivityEntity> implements BargainActivityService {

    @Autowired
    private FeginService feginService;

    @Autowired
    private BargainingItemDao bargainingItemDao;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BargainActivityService bargainActivityService;

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private BargainingRecordDao bargainingRecordDao;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<BargainActivityEntity> page = this.page(
                new Query<BargainActivityEntity>().getPage(params),
                new QueryWrapper<BargainActivityEntity>()
        );

        List<BargainActivityEntity> records = page.getRecords();
        for (BargainActivityEntity record : records) {
            GoodsEntity goodsEntity = goodsDao.selectOne(new QueryWrapper<GoodsEntity>().eq("id", record.getGoodsId()));
            record.setGoodsEntity(goodsEntity);
        }
        page.setRecords(records);
        return new PageUtils(page);
    }

    @Override
    public void savesj(BargainActivityEntity bargainActivity) {
        baseMapper.insertsj(bargainActivity);
    }

    @Override
    public void savedd(kVo kvo) {

        String count = redisTemplate.opsForValue().get(kvo.getUid() + "count"+kvo.getId());
        //根据活动id查询到
        QueryWrapper<BargainActivityEntity> idd = new QueryWrapper<BargainActivityEntity>().eq("id", kvo.getBid());
        BargainActivityEntity ActivityEntity = baseMapper.selectOne(idd);
        //两种砍价模式  1. 规定次数 在次数内能砍到最低价 2. 没有次数上限，金额能看到最低
        if (!ActivityEntity.getShopBargainingRules().equals(1)){
            //没有次数上限，金额能看到最低

            //取出之前的砍价 以及商品信息
            GoodsEntity goodsEntity = new GoodsEntity();
            BeanUtils.copyProperties(kvo, goodsEntity);// 将实体类进行赋值 并将最新的商品信息存入redis中
            System.out.println(goodsEntity);
            String s1 = redisTemplate.opsForValue().get(goodsEntity.getId() + "," + kvo.getUid());
            if (s1==null){
                ArrayList<GoodsEntity> goodses = new ArrayList<>();
                goodses.add(goodsEntity);

                Random random = new Random();
                //随机砍价  保证不能一刀砍成
                int i1 = random.nextInt((int) ((Integer.parseInt(String.valueOf(goodsEntity.getGoodsPrice()))-kvo.getDj())*0.2));
                String s = feginService.feginGetName(Long.valueOf(kvo.getUid()));
//添加个人记录表
                BargainingRecordEntity bargainingRecordEntity = new BargainingRecordEntity();
                bargainingRecordEntity.setBaId(Long.valueOf(kvo.getKhdid()));
                bargainingRecordEntity.setUid(Long.valueOf(kvo.getUid()));
                bargainingRecordEntity.setGoodsId(Math.toIntExact(kvo.getId()));
                bargainingRecordEntity.setKnifeName(s);
//              //计算砍了多少钱
                bargainingRecordEntity.setKnifePrice(BigDecimal.valueOf(i1));
                bargainingRecordEntity.setSyMoney(Integer.parseInt(String.valueOf(goodsEntity.getGoodsPrice())) - i1);
                System.out.println(bargainingRecordEntity);
                int insert = bargainingRecordDao.insert(bargainingRecordEntity);
                System.out.println(insert);


              //  goodsEntity.setGoodsPrice(BigDecimal.valueOf(Integer.parseInt(String.valueOf(kvo.getGoodsPrice())) - i1));
                goodsEntity.setGoodsPrice(BigDecimal.valueOf(bargainingRecordEntity.getSyMoney()));
                //对集合添加每个实体类
                goodses.add(goodsEntity);
                System.out.println("为转json"+goodses);
                System.out.println("转json"+JSON.toJSONString(goodses));
                redisTemplate.opsForValue().set(goodsEntity.getId() + "," + kvo.getUid(), JSON.toJSONString(goodses));
                //添加订单状态信息
                BargainingItemEntity itemEntity = new BargainingItemEntity();
                String snowflakeId = SnowflakeIdWorker.getSnowflakeId();
                System.out.println(snowflakeId);
                itemEntity.setId(Long.valueOf(snowflakeId));
                itemEntity.setUid(Long.valueOf(kvo.getUid()));
                itemEntity.setGoodsPrice(goodsEntity.getGoodsPrice());
                itemEntity.setGoodsId(Math.toIntExact(goodsEntity.getId()));
                itemEntity.setBkhdId(Long.valueOf(kvo.getKhdid()));
                itemEntity.setXgTime(new Date());
                rabbitTemplate.convertAndSend("kj.order",JSONObject.toJSONString(itemEntity));
            }else{
                List<GoodsEntity> goodsEntities = JSONObject.parseObject(s1, new TypeReference<List<GoodsEntity>>() {
                });
                System.out.println("从redis中取出的商品信息  以及砍到的价格" + goodsEntities);
                //获取最近一次更新
                GoodsEntity goodsEntity1 = goodsEntities.get(goodsEntities.size() - 1);

                Random random = new Random();
                // int i1 = random.nextInt(Integer.parseInt(String.valueOf(kvo.getGoodsPrice())) - kvo.getDj());
                int i1 = random.nextInt(Integer.parseInt(String.valueOf(goodsEntity1.getGoodsPrice())));

                System.out.println("砍价金额: " + i1);
                //判断
                if (i1 == Integer.parseInt(String.valueOf(goodsEntity1.getGoodsPrice()))) {
                    bargainActivityService.savedd(kvo);
                }
                String s = feginService.feginGetName(Long.valueOf(kvo.getUid()));


                //添加个人记录表
                BargainingRecordEntity bargainingRecordEntity = new BargainingRecordEntity();
                bargainingRecordEntity.setBaId(Long.valueOf(kvo.getKhdid()));
                bargainingRecordEntity.setUid(Long.valueOf(kvo.getUid()));
                bargainingRecordEntity.setGoodsId(Math.toIntExact(kvo.getId()));
                bargainingRecordEntity.setKnifeName(s);

//              //计算砍了多少钱
                bargainingRecordEntity.setKnifePrice(BigDecimal.valueOf(i1));
                bargainingRecordEntity.setSyMoney(Integer.parseInt(String.valueOf(goodsEntity1.getGoodsPrice())) - i1);
                System.out.println(bargainingRecordEntity);
                int insert = bargainingRecordDao.insert(bargainingRecordEntity);
                System.out.println(insert);


             //   goodsEntity.setGoodsPrice(BigDecimal.valueOf(Integer.parseInt(String.valueOf(kvo.getGoodsPrice())) - i1));
                goodsEntity.setGoodsPrice(BigDecimal.valueOf(bargainingRecordEntity.getSyMoney()));
                //对集合添加每个实体类
                goodsEntities.add(goodsEntity);
                redisTemplate.opsForValue().set(goodsEntity.getId() + "," + kvo.getUid(), JSON.toJSONString(goodsEntities));
                //修改订单状态信息
                QueryWrapper<BargainingItemEntity> eq = new QueryWrapper<BargainingItemEntity>().eq("uid", kvo.getUid()).eq("goods_user_static", 0);
                BargainingItemEntity bargainingItemEntity = bargainingItemDao.selectOne(eq);
                bargainingItemEntity.setGoodsPrice(goodsEntity.getGoodsPrice());
                bargainingItemEntity.setXgTime(new Date());
                rabbitTemplate.convertAndSend("kj.indent",JSONObject.toJSONString(bargainingItemEntity));
            }
        }else{
        //判断数量
        if (StringUtils.isEmpty(count)) { //代表第一次砍价 金额占80%

            //第一次砍价本人砍  砍80%
            int i = (int) ((Integer.parseInt(String.valueOf(kvo.getGoodsPrice())) - kvo.getDj()) * 0.8);
            String s = feginService.feginGetName(Long.valueOf(kvo.getUid()));

            //存入商品砍价的次数  商品砍价信息  以及每砍一次的数据实时更新到redis
            System.out.println("");
            redisTemplate.opsForValue().set(kvo.getUid() + "count"+kvo.getId(), "1");
            GoodsEntity goodsEntity = new GoodsEntity();
            BeanUtils.copyProperties(kvo, goodsEntity);// 将实体类进行赋值 并将最新的商品信息存入redis中
            //存入list的商品集合
            ArrayList<GoodsEntity> goodsEntities = new ArrayList<>();
            goodsEntity.setGoodsPrice(BigDecimal.valueOf(Integer.parseInt(String.valueOf(kvo.getGoodsPrice())) - i));
            String uid = kvo.getUid();
            //对集合添加每个实体类
            goodsEntities.add(goodsEntity);
            redisTemplate.opsForValue().set(goodsEntity.getId() + "," + uid, JSON.toJSONString(goodsEntities));


            BargainingRecordEntity bargainingRecordEntity = new BargainingRecordEntity();
            bargainingRecordEntity.setBaId(Long.valueOf(kvo.getKhdid()));
            bargainingRecordEntity.setUid(Long.valueOf(kvo.getUid()));
            bargainingRecordEntity.setGoodsId(Math.toIntExact(kvo.getId()));
            bargainingRecordEntity.setKnifeName(s);
            //计算砍了多少钱
            bargainingRecordEntity.setKnifePrice(BigDecimal.valueOf(i));
            bargainingRecordEntity.setSyMoney(Integer.parseInt(String.valueOf(kvo.getGoodsPrice())) - i);
            System.out.println(bargainingRecordEntity);
            int insert = bargainingRecordDao.insert(bargainingRecordEntity);
            System.out.println(insert);

            //添加订单状态信息
            BargainingItemEntity itemEntity = new BargainingItemEntity();
            String snowflakeId = SnowflakeIdWorker.getSnowflakeId();
            System.out.println(snowflakeId);
            itemEntity.setId(Long.valueOf(snowflakeId));
            itemEntity.setUid(Long.valueOf(kvo.getUid()));
            itemEntity.setGoodsPrice(BigDecimal.valueOf(bargainingRecordEntity.getSyMoney()));
            itemEntity.setGoodsId(Math.toIntExact(goodsEntity.getId()));
            itemEntity.setBkhdId(Long.valueOf(kvo.getKhdid()));
            itemEntity.setXgTime(new Date());
            rabbitTemplate.convertAndSend("kj.order",JSONObject.toJSONString(itemEntity));
        } else {

            //根据活动id查询到
            QueryWrapper<BargainActivityEntity> id = new QueryWrapper<BargainActivityEntity>().eq("id", kvo.getBid());
            BargainActivityEntity bargainActivityEntity = baseMapper.selectOne(id);

            if (bargainActivityEntity.getKafinSunCount() == Integer.valueOf(count)) {
                //满足人数  直接可以支付
                //........
            } else {
                //取出之前的砍价 以及商品信息
                GoodsEntity goodsEntity = new GoodsEntity();
                BeanUtils.copyProperties(kvo, goodsEntity);// 将实体类进行赋值 并将最新的商品信息存入redis中
                System.out.println(goodsEntity);
                String s1 = redisTemplate.opsForValue().get(goodsEntity.getId() + "," + kvo.getUid());
                List<GoodsEntity> goodsEntities = JSONObject.parseObject(s1, new TypeReference<List<GoodsEntity>>() {
                });
                System.out.println("从redis中取出的商品信息  以及砍到的价格" + goodsEntities);
                //获取最近一次更新
                GoodsEntity goodsEntity1 = goodsEntities.get(goodsEntities.size() - 1);

                Random random = new Random();
                // int i1 = random.nextInt(Integer.parseInt(String.valueOf(kvo.getGoodsPrice())) - kvo.getDj());
                int i1 = random.nextInt(Integer.parseInt(String.valueOf(goodsEntity1.getGoodsPrice())));

                System.out.println("砍价金额: " + i1);
                //判断
                if (i1 == Integer.parseInt(String.valueOf(goodsEntity1.getGoodsPrice()))) {
                    bargainActivityService.savedd(kvo);
                }
                String s = feginService.feginGetName(Long.valueOf(kvo.getUid()));


                //添加个人记录表
                BargainingRecordEntity bargainingRecordEntity = new BargainingRecordEntity();
                bargainingRecordEntity.setBaId(Long.valueOf(kvo.getKhdid()));
                bargainingRecordEntity.setUid(Long.valueOf(kvo.getUid()));
                bargainingRecordEntity.setGoodsId(Math.toIntExact(kvo.getId()));
                bargainingRecordEntity.setKnifeName(s);
//              //计算砍了多少钱
                bargainingRecordEntity.setKnifePrice(BigDecimal.valueOf(i1));
                bargainingRecordEntity.setSyMoney(Integer.parseInt(String.valueOf(goodsEntity1.getGoodsPrice())) - i1);
                System.out.println(bargainingRecordEntity);
            int insert = bargainingRecordDao.insert(bargainingRecordEntity);
            System.out.println(insert);


                goodsEntity.setGoodsPrice(BigDecimal.valueOf(Integer.parseInt(String.valueOf(kvo.getGoodsPrice())) - i1));
                //对集合添加每个实体类
                goodsEntities.add(goodsEntity);
                redisTemplate.opsForValue().set(goodsEntity.getId() + "," + kvo.getUid(), JSON.toJSONString(goodsEntities));
                redisTemplate.opsForValue().set(kvo.getUid() + "count"+kvo.getId(), String.valueOf(Integer.parseInt(count) + 1));
                //修改订单状态信息
                QueryWrapper<BargainingItemEntity> eq = new QueryWrapper<BargainingItemEntity>().eq("uid", kvo.getUid()).eq("goods_user_static", 0);
                BargainingItemEntity bargainingItemEntity = bargainingItemDao.selectOne(eq);
                bargainingItemEntity.setGoodsPrice(BigDecimal.valueOf(bargainingRecordEntity.getSyMoney()));
                bargainingItemEntity.setXgTime(new Date());
                rabbitTemplate.convertAndSend("kj.indent",JSONObject.toJSONString(bargainingItemEntity));
            }
        }

        }

    }

    @Override
    public BargainActivityEntity getByIda(Long bid) {
        QueryWrapper<BargainActivityEntity> wrapper = new QueryWrapper<>();
        QueryWrapper<BargainActivityEntity> id = wrapper.eq("id", bid);
        BargainActivityEntity bargainActivityEntity = baseMapper.selectOne(id);
        return bargainActivityEntity;
    }

}